package kr.hkit.powerjava.chapter24.work;

import java.util.Comparator;
import java.util.Scanner;

public class ServiceStudent {

	
	//1. 시작(StudentDao 객체 생성 , loadfile())
	//2. 메뉴출력(prnMenu)
	//3. 종료(StudentDao.sava())
	
	private StudentDao dao;
	
	private Scanner sc;
	
	public ServiceStudent(){
		dao = new StudentDao();
		sc = new Scanner(System.in);
		init();
	}
	
	public ServiceStudent(StudentDao dao) {
		this.dao = dao;
		sc = new Scanner(System.in);
		init();
	}



	private void init() {
		dao.loadFile();
		prnMenu();
	}

	private void prnMenu() {
		int res = 0;
		Student std = null;
		do{
			System.out.print("1.입력\n2.삭제\n3.수정\n4.검색\n5.리스트보기\n6.종료\n");
			res = sc.nextInt();
			switch(res){
				case 1://입력
					//학생정보 입력
					std = inputStdInfo(true);
					dao.insertData(std);
					break;
				case 2://삭제
					//리스트를 보여주고 삭제할 번호 입력 받음 
					dao.prnData(null);
					System.out.print("삭제할 학생정보를 입력");
					std = inputStdInfo(false);
					dao.deleteData(std);
					break;
				case 3://수정
					// 리스트를 보여주고 수정할 학생 정보를 입력 받음
					dao.prnData(null);
					System.out.println("수정할 번호를 입력하시오");
					int updateNum = sc.nextInt();
					std = inputStdInfo(true);
					dao.updateData(std);
					break;
				case 4://검색
					std = inputStdInfo(false);
					try{
					std = dao.searchData(std);
					System.out.println(std);
					}catch(ArrayIndexOutOfBoundsException e){
						System.out.println("학생정보 음슴");
					}
					break;
				case 5://리스트
					prnSubMenu();
					break;
				case 6://종료
					dao.saveFile();
					sc.close();
					System.exit(0);
					break;
				default:
					res = 6;
			}
		}while (res <=6);
		
	}

	private Student inputStdInfo(boolean b) {
		System.out.println("학번 성명");
		int num = sc.nextInt();
		String name = sc.next();
		
		if(b){
			System.out.println("국 영 수");
			int kor = sc.nextInt();
			int eng = sc.nextInt();
			int math = sc.nextInt();
			return new Student(num, name, kor, eng, math);
		}else{
			return new Student(num, name);
		}
	}

	private void prnSubMenu() {
		System.out.print("1. 이름순 2. 성적순 3.번호순");
		int res = sc.nextInt();
		switch (res){
			case 1:
				dao.prnData(new Comparator<Student>() {
					
					@Override
					public int compare(Student o1, Student o2) {
						
						return o1.getStdName().hashCode() - o2.getStdName().hashCode();
					}
				});
				break;
			case 2:
				dao.prnData(new Comparator<Student>() {
					
					@Override
					public int compare(Student o1, Student o2) {
						
						return o1.totalScore() - o2.totalScore();
					}
				});
				break;
			case 3:
				dao.prnData(null);
				break;
			default:
				dao.prnData(null);
		}
		
	}
}
